package longrise.phone.com.bjjt_henan.lunchandlogin;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.LFView;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.EnCryptDeCrypt;
import com.longrise.bjjt.util.PrefUtils;
import com.longrise.bjjt.util.UiUtil;

import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.main.NewMainView;

/**
 * Created by Administrator on 2016/5/11.
 */
public class HeNanLoginView extends LFView implements View.OnClickListener, ILSMsgListener {
    private Context context = null;
    private View view = null;
    private TextView tv_login_fastregister;
    private TextView iv_login_text1;
    private EditText et_login1;
    private EditText et_login2;
    private Button bt_login_ensure;
    private Dialog dialog;
    private LinearLayout pwdLayout;

    public HeNanLoginView(Context context) {
        super(context);
        this.context = context;
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {

        return null;
    }

    @Override
    public void refresh() {

    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);// 注册事件
        setLastLogin();
    }

    private void initView() {
        view = View.inflate(context, R.layout.view_henanlogin, null);
        tv_login_fastregister = (TextView) view.findViewById(R.id.tv_login_fastregister);
        iv_login_text1 = (TextView) view.findViewById(R.id.iv_login_text1);
        et_login1 = (EditText) view.findViewById(R.id.et_login1);
        et_login2 = (EditText) view.findViewById(R.id.et_login2);
        bt_login_ensure = (Button) view.findViewById(R.id.bt_login_ensure);
        pwdLayout = (LinearLayout) view.findViewById(R.id.login_layout_pwd);
    }

    private void regEvent(boolean b) {
        if (null != tv_login_fastregister) {
            tv_login_fastregister.setOnClickListener(b ? this : null);
        }
        if (null != iv_login_text1) {
            iv_login_text1.setOnClickListener(b ? this : null);
        }
        if (null != bt_login_ensure) {
            bt_login_ensure.setOnClickListener(b ? this : null);
        }
        if (null != pwdLayout) {
            pwdLayout.setOnClickListener(b ? this : null);
        }
        if (b) {
            this.addILSMsgListener(this);
        } else {
            this.removeILSMsgListener(this);
        }
    }

    public void setLastLogin() {
        if (null != et_login2) {
            String name = PrefUtils.getString(context, "loginUserName", "");
            et_login1.setText(name);
        }
        if (null != et_login2) {
            String pwd = PrefUtils.getString(context, "loginPassword", "");
            et_login2.setText(pwd);
        }
    }

    @Override
    public Object onLSMsg(int i, Object... objects) {
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login_fastregister:
                RegisterView registerview = new RegisterView(context);
                FrameworkManager.getInstance().showNewForm(context, registerview);
                break;
            case R.id.iv_login_text1:
                ForgetPasswordView forgetpasswordview = new ForgetPasswordView(context);
                FrameworkManager.getInstance().showNewForm(context, forgetpasswordview);
                break;
            case R.id.bt_login_ensure:
                String et_login1Content = et_login1.getText().toString().trim();
                String et_login2Content = et_login2.getText().toString().trim();
                if (TextUtils.isEmpty(et_login1Content)) {
                    UiUtil.showToast(context, "手机号不能为空");
                } else if (TextUtils.isEmpty(et_login2Content)) {
                    UiUtil.showToast(context, "密码不能为空");
                } else {
                    //联网登陆
                    login(et_login1Content, et_login2Content);
                    break;
                }
                break;
            case R.id.login_layout_pwd:
                CommontUtils.setSeePwd(et_login2);
                setShowDrawable(et_login2, (ImageView) view.findViewById(R.id.login_iv_pwd));
                break;
        }
    }

    //设置明文密码时的图像标识
    private void setShowDrawable(EditText editText, ImageView imageView) {
        TransformationMethod method = editText.getTransformationMethod();
        if (method instanceof PasswordTransformationMethod) {
            imageView.setImageResource(R.mipmap.eye);
        } else {
            imageView.setImageResource(R.mipmap.eye_select);
        }
    }

    //设置登录参数，用户超时会自动登录
    private void setLoginBean(String name, String pwd) {
        EntityBean bean = new EntityBean();
        bean.set(LoadDataManagerFather.IP_KEY_NAME, context.getResources().getString(R.string.kckpServerUrl));
        bean.set(LoadDataManagerFather.SERVICENAME_KEY_NAME, URLConstant.LOGIN);
        EntityBean dataBean = new EntityBean();
        dataBean.set("userflag", name);
        dataBean.set("password", pwd);
        bean.set(LoadDataManagerFather.PARAMBEAN_KEY_NAME, dataBean);
        LoadDataManagerCar.getInstance(context).setLoginInfoBean(bean);
    }

    /**
     * 联网登陆
     *
     * @param userNametologin
     * @param passwordtologin
     */
    private void login(final String userNametologin, final String passwordtologin) {
        try {
            EntityBean bean = new EntityBean();
            bean.set("userflag", userNametologin);
            final String pwd = EnCryptDeCrypt.getInstance().EnCrypt(passwordtologin);
            bean.set("password", pwd);
            dialog = UiUtil.showProcessDialog(context, "登录中...");
            LoadDataManagerCar.getInstance(context).callService(null,
                    ((BaseApplication) context.getApplicationContext()).getBaseServerUrl(),
                    URLConstant.LOGIN, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                        @Override
                        public void onSuccess(String key, String service, Object result) {
                            Log.i("applogin", result.toString());
                            if (null != dialog) {
                                dialog.dismiss();
                            }
                            String noticeStr = null;
                            String restate = null;
                            if (null != result) {
                                restate = ((EntityBean) result).getString("restate");
                                noticeStr = ((EntityBean) result).getString("redes", "");
                            }
                            if ("1".equals(restate)) {
                                EntityBean bean = ((EntityBean) result).getBean("data");
                                if (null != bean) {
                                    String token = bean.getString("token", "");
                                    String userflag = bean.getBean("userinfo").getString("userflag");
                                    BaseApplication application = (BaseApplication) context.getApplicationContext();
                                    //缓存数据
                                    application.setToken(token);
                                    application.setLoginInfo(bean);
                                    application.setKckpName(userflag);
                                    application.setKckpPass(pwd);
                                }

                                // 将菜单存到本地
                                String userInfoStr = com.longrise.LEAP.Base.IO.JSONSerializer.getInstance().Serialize(bean);
                                PrefUtils.setString(context, "loginInfo", userInfoStr);

                                // 保存用户名和密码到本地
                                PrefUtils.setString(context, "loginUserName", userNametologin);
                                PrefUtils.setString(context, "loginPassword", passwordtologin);
                                // add by huxin,判断来自其他LFview，进行消息传递
                                LSMsgCall(0x1109, 1010);
                           /* // add by huxin

                            if (null != onLoginFormCloseListener) {
                                onLoginFormCloseListener.onLoginClose(LoginView.this, true);
                            }
*/
                                et_login1.setText("");
                                et_login2.setText("");
                                setLoginBean(userNametologin, pwd);

                                NewMainView homepageview = new NewMainView(context);
                                FrameworkManager.getInstance().showNewForm(context, homepageview);
                                closeForm();
                            } else {
                                UiUtil.showToast(getContext(), noticeStr);
                            }
                        }

                        @Override
                        public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                            if (null != dialog) {
                                dialog.cancel();
                            }
                            if (resultType == LoadDataManagerFather.ResultType.Failure) {
                                UiUtil.showToast(getContext(), "网络服务故障，请稍后重试");
                            } else if (resultType == LoadDataManagerFather.ResultType.NoNetWorks) {
                                UiUtil.showToast(getContext(), "无网络连接，请检查您的网络");
                            }
                        }

                        @Override
                        public void onFinished(String key, String service) {
                            if (null != dialog) {
                                dialog.cancel();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        view = null;
        tv_login_fastregister = null;
        iv_login_text1 = null;
        et_login1 = null;
        et_login2 = null;
        bt_login_ensure = null;
        dialog = null;
    }
}
